<template>
	<div class="merak-container-has-aside">
		<div class="merak-aside">
			<div class="title">商品类型</div>
			<el-input v-model="treeState.filter" :placeholder="$t('merak.placeholder_filter')"
				@input="value => treeRef?.filter(value)" />
			<div class="tree-wrapper">
				<el-scrollbar>
					<el-tree ref="treeRef" node-key="value" :data="treeState.data" :props="{ children: 'childs' }"
						:default-expanded-keys="expandedKeys"
						:filter-node-method="(value, tree) => tree.label.includes(value)"
						@current-change="handleCurrentChange" />
				</el-scrollbar>
			</div>
		</div>
		<div v-waterMarker class="merak-card merak-container-has-search">
			<searchBar close-enter close-plan close-advanced custom-class="searchHeaderDaily"
				:placeholder="$t('archive_set_producingCountry.producing_country')" ref="searchbar"
				@search-event="searchBarPost">
				<template #header>
					<el-select filterable style="width: 200px;" v-if="state.thisPageDate.type_id != 0 && state.thisPageDate.type_id != ''"  v-model="state.thisPageDate.size_standard_id" value-key="key"   clearable :placeholder="$t('set_standardGroup.size_standard_id')" >
						<el-option v-for="oItem in opstionsObjs.sizeStandardList" :key="oItem.value" :label="oItem.label"
							:value="oItem.value" />
					</el-select>
					<el-select filterable style="width: 200px;margin-left: 10px;" v-if="state.thisPageDate.type_id != 0 && state.thisPageDate.type_id != ''"  v-model="state.thisPageDate.size_id" value-key="key"   clearable :placeholder="$t('set_standardGroup.size_id')" >
						<el-option v-for="oItem in opstionsObjs.sizeList" :key="oItem.value" :label="oItem.label"
							:value="oItem.value" />
					</el-select>
				</template>
				<template #footer>
					<el-button type="primary" @click="addCountry"
						v-if="countryAuth?.add?.show">{{$t('set_standardGroup.add_standard')}}</el-button>
				</template>
			</searchBar>
			<!-- 表格组件 -->
			<div class="merak-table-wrapper">
				<MerakXTable ref="tableRef" v-bind="tablePayload" :batch-click="handleBatchClick"
					:handler-click="handleHanderClick" :query-columns="queryColumns" :query-data="queryData">
					<template #funBtn="{row}">
						<div class="action_btn">
							<el-button class="qf_btn_auto" type="primary" v-if="countryAuth?.edit?.show" link
								@click="goEdit(row)"> {{$t('merak.edit')}}
							</el-button>
							<!-- <el-button class="qf_btn_auto" :disabled="row.used == 0 ? false :true" type="danger" link v-if="countryAuth?.delete?.show" @click="goDelete(row)">{{$t('merak.delete')}} 
						</el-button> -->
						</div>
					</template>
				</MerakXTable>
			</div>
			<el-dialog v-model="model" style="width: 500px;" align-center append-to-body>
				<template #header>
					<div class="editor-title" v-if="countryId != ''">
						{{$t('set_standardGroup.edit_standard')}}</div>
					<div class="editor-title" v-else>{{$t('set_standardGroup.add_standard')}}</div>
				</template>
				<el-form ref="ruleFormRef" label-position="top" :model="ruleForm" :rules="rules">
					<el-form-item prop="type_id" :label="$t('set_standardGroup.type_id')">
						<el-select filterable class="qf_select" :placeholder="$t('merak.placeholder_select')"
							v-model="ruleForm.type_id" @change="showSizeList">
							<el-option :label="item?.label" :value="item?.value" v-for="item in opstionsObjs?.typeList"
								:key="item?.value" />
						</el-select>
					</el-form-item>
					<el-form-item prop="size_standard_id" :label="$t('set_standardGroup.size_standard_id')">
						<el-select filterable class="qf_select" :placeholder="$t('merak.placeholder_select')"
							v-model="ruleForm.size_standard_id">
							<el-option :label="item?.label" :value="item?.value"
								v-for="item in opstionsObjs?.sizeStandardList" :key="item?.value" />
						</el-select>
					</el-form-item>
					<el-form-item  prop="size_id" :label="$t('set_standardGroup.size_id')">
						<el-select v-if="countryId == ''" filterable multiple class="qf_select" :placeholder="$t('merak.placeholder_select')"
							v-model="ruleForm.size_id">
							<el-option :label="item?.label" :value="item?.value" v-for="item in opstionsObjs?.sizeList"
								:key="item?.value" />
						</el-select>
						<el-select v-else filterable class="qf_select" :placeholder="$t('merak.placeholder_select')"
							v-model="ruleForm.size_id">
							<el-option :label="item?.label" :value="item?.value" v-for="item in opstionsObjs?.sizeList"
								:key="item?.value" />
						</el-select>
					</el-form-item>
				</el-form>
				<template #footer>
					<el-button @click="cancenForm(ruleFormRef)">{{ $t("merak.cancel") }}</el-button>
					<el-button type="primary" :disabled="disabled" :loading="loading"
						@click="submitForm(ruleFormRef)">{{ $t("merak.confirm") }}</el-button>
				</template>
			</el-dialog>
		</div>
	</div>
</template>

<script setup lang="tsx" name="standardGroup">
	import type {
		FormInstance,
		FormRules,
	} from "element-plus";
	import {
		reactive,
		computed,
		watch,
		onMounted,
		ref,
		getCurrentInstance
	} from "vue";
	import searchBar from "@/components/SearchBar";
	import TreeFilter from "@/components/TreeFilter/index.vue";
	import MerakXTable, {
		MerakXTableInstance,
		MerakXTableProps
	} from "@/components/MerakXTable";

	import {
		getCountryHead,
		getCountryList,
		addCountryItem,
		deleteCountryItem
	} from "@/api/modules/goodsArchive/set/producingCountry";
	import {
		getSizeStandard,
		letTree,
		addData,
		editData,
		initData,
		getTableHeader,
		getTableData
	} from "@/api/modules/goodsArchive/standardGroup";
	import {
		failMsg,
		successMsg
	} from "@/utils/messageUtils";
	import {
		ElMessageBox,
		ElMessage
	} from "element-plus";
	import {
		UserAuthType,
		getUserAuth
	} from "@/api/modules/user";
	import {
		useRoute
	} from "vue-router";
	const route = useRoute();
	const tableRef = ref < MerakXTableInstance > ();
	const ruleFormRef = ref < FormInstance > ()
	const treeRef = ref < InstanceType < typeof ElTree >> ();
	const countryAuth = ref({}) //权限
	const {
		proxy
	} = getCurrentInstance() !;
	const expandedKeys = computed(() => {
		const arr: string[] = [];
		if (!!route.query.key) {
			const routeKeys = route.query.key.toString().split("-");
			arr.push(routeKeys[0]);
		}
		return arr;
	});
	// 页面配置数据
	const state = reactive < {
		thisPageDate: Record < string,
		string > ;
	} > ({
		thisPageDate: {
			type_id: '',
			size_standard_id:''
		},
	
	});
	const treeState = reactive < {
		data: TreeType[];
		value ? : string;
		filter ? : any;
	} > ({
		data: []
	});
	const changeTreeFilter = (row) => {
		page_parents_id.value = row.id;
		curlevel.value = row.level;

		if (curlevel.value < 2) {
			return false;
		}



		// 构建新的URL
		const newUrl = new URL(window.location.href);
		//console.log(newUrl)
		newUrl.searchParams.set('id', row.id);
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());

	};
	const model = ref(false) //新增、编辑弹窗
	//页面的select下拉数据
	const opstionsObjs = reactive({
		typeList: [], //商品类型
		sizeStandardList: [], //码制
		sizeList: [], //尺码
	})
	let ruleForm = reactive({
		"type_id": "", //排序
		"size_standard_id": "", //码制
		"size_id": "", //尺码
	})
	const countryId = ref("") //国家id
	
	watch(
	  ()=> state.thisPageDate.type_id,
	  (newValue, oldValue) => {
		  console.log(newValue)
	    showSizeList(newValue)
	  },
	  { once: true }
	)
	// 树点击
	const handleCurrentChange: InstanceType < typeof ElTree > ["onCurrent-change"] = (data, treeNode) => {
		if (!treeNode.isLeaf) return;
		const url = new URL(location.href);
		url.searchParams.set("key", data.value.toString());
		if(data.value != 0 ){
			showSizeList(data.value.toString())
		} else {
			state.thisPageDate.size_standard_id = ''
		}
		state.thisPageDate.type_id = data.value.toString();
		ruleForm.type_id = data.value.toString();
		// 记录浏览器参数
		history.pushState({}, "", url);
		treeRef.value?.setCheckedKeys([data.value]);
	};
	const rules = reactive({
		type_id: [{
			required: true,
			message: proxy!.$t("goods_attribute.require"),
			trigger: 'blur',
		}, ],
		size_standard_id: [{
			required: true,
			message: proxy!.$t("goods_attribute.require"),
			trigger: 'blur',
		}, ],
		size_id: [{
			required: true,
			message: proxy!.$t("goods_attribute.require"),
			trigger: 'blur',
		}, ],
	})

	// 动态计算表格的外部筛选数据
	const params = computed(() => ({
		...state.thisPageDate
	}));

	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "user_id",
		// 初始化的外部筛选数据
		params,
		awaitParams:true,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		// ["selection", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
		columnType: [{
			type: 'handle',
			width: 100,
			slot: 'funBtn'
		}],

	});

	// 获取表头数据
	const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
		return getTableHeader().then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				return {
					...data,
					columns: [...data.columns].map(column => {
						switch (column.field) {
							case "exception_type_off":
								// column.slots = {
								// 	default: "employee_one"
								// };
								return column;
							default:
								return column;
						}
					})
				};
			}
		});
	};

	/**
	 * 获取表格数据
	 * @param page 分页参数
	 * @param sorts 多重排序参数
	 * @param filters 表头筛选参数
	 * @param from 外部由 tablePayload.params 传入的自定义参数
	 */
	const queryData: MerakXTableInstance["queryData"] = async ({
		page,
		sorts,
		from
	}) => {
		// 创建请求表格数据的参数
		const params: Record < string, any > = {};
		// 如果有分页数据
		if (!!page) {
			Object.assign(params, {
				...page
			});
		}
		// 如果有排序数据
		if (!!sorts) {
			for (let sort of sorts.values()) {
				console.log(sort);
			}
		}
		// 如果有自定义参数
		if (!!from) {
			for (let key of Object.keys(from)) {
				const item = from[key];
				!!item && (params[key] = item);
			}
		}
		// 初始化接口需要传入队列 loading 暴露的 id
		return getTableData(params).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				return data.table_data;
			}
		});
	};
	
	const cancenForm = async (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		model.value = false
	}

	const submitForm = async (formEl: FormInstance | undefined, isHide: boolean) => {

		if (!formEl) return
		await formEl.validate((valid, fields) => {
			//failMsg('所有的属性值(中文)、属性值(俄文)不能为空')
			if (valid) {
				let postData = ruleForm;
				if (countryId.value != "") {
					postData.id = countryId.value;
					editData(postData).then(({
						code,
						data,
						message
					}) => {
						if (code == 2000) {
							formEl.resetFields();
							ruleForm.type_id = "";
							ruleForm.size_standard_id = "";
							ruleForm.size_id = "";
							countryId.value = "";
							tableRef.value?.reloadData();
							model.value = false;
						} else {
							failMsg(message)
						}
					})
				} else {
					addData(postData).then(({
						code,
						data,
						message
					}) => {
						if (code == 2000) {
							formEl.resetFields();
							ruleForm.type_id = "";
							ruleForm.size_standard_id = "";
							ruleForm.size_id = "";
							countryId.value = "";
							tableRef.value?.reloadData();
							model.value = false;
						} else {
							failMsg(message)
						}
					})
				}

				
			} else {
				console.log('error submit!', fields)
			}
		})
	}
	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {
		//console.log(params)
		let postParams = {
			...params.params,
		};
		state.thisPageDate.keyword = params.search;
	};
	
	const showSizeList = row => {
		//queryStatData();
		let dataMsg = {
			type_id:row
		}
		getSizeStandard(dataMsg).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				//countryAuth.value = data
				opstionsObjs.sizeStandardList= data?.size_standard_id; //码制
				opstionsObjs.sizeList= data?.size_id; //尺码
			}
		});
	};
	
	const init = async () => {
		//queryStatData();
		getUserAuth("standardGroup").then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				countryAuth.value = data
			}
		});
	};
	const getData = async (id) => {
		//queryStatData();
		let dataMsg = {
			id: id
		}
		initData(dataMsg).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				opstionsObjs.typeList= data.dataarr?.type_id; //商品类型
				opstionsObjs.sizeStandardList= data.dataarr?.size_standard_id; //码制
				opstionsObjs.sizeList= data.dataarr?.size_id; //尺码
			}
		});
	};
	const initDataMsg = async () => {
		//queryStatData();
		letTree().then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				treeState.data = data;
				if (!!route.query.key) {
					const routeKeys = route.query.key.toString().split("-");
					state.thisPageDate.type_id = routeKeys[routeKeys.length - 1];
					treeRef.value?.setCheckedKeys([route.query.key.toString()]);
				} else {
					state.thisPageDate.type_id = "0";
					treeRef.value?.setCheckedKeys(["0"]);
				}
			}
		});
	};
	const addCountry = () => {
		model.value = true;
		countryId.value = ""
		ruleForm.type_id = ""
		ruleForm.size_standard_id = ""
		ruleForm.size_id = ""
	};

	const goEdit = row => {
		console.log(row)
		model.value = true;
		countryId.value = row.size_standard_group_id
		ruleForm.type_id = row.type_id
		ruleForm.size_standard_id = row.size_standard_id_val
		ruleForm.size_id = row.size_id_val
		getData(row.size_standard_group_id)
	};
	// const goDelete = row => {
	// 	let data = {
	// 		manufacturer_county_id: row.manufacturer_county_id
	// 	}
	// 	ElMessageBox.confirm(proxy!.$t("archive_set_producingCountry.country_warning"), proxy!.$t("merak.tip_modal"), {
	// 		confirmButtonText: proxy!.$t("merak.confirm"),
	// 		cancelButtonText: proxy!.$t("merak.cancel"),
	// 		type: "warning"
	// 	}).then(() => {
	// 		deleteCountryItem(data).then(({
	// 			code,
	// 			data,
	// 			message
	// 		}) => {
	// 			if (code == 2000) {
	// 				tableRef.value?.reloadData();
	// 				successMsg(proxy!.$t("merak.delete_success"));
	// 			} else {
	// 				failMsg(message)
	// 			}
	// 		})

	// 	});

	// };

	onMounted(() => {
		init();
		initDataMsg();
		getData("")
	})
</script>

<style type="text/css" scoped>
	@import "./index.scss";
</style>